from django.shortcuts import render
from course.models import Course,CourseExpire
# Create your views here.
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class CartView(ViewSet):
    # authentication_classes =
    permission_classes = [IsAuthenticated, ]  #request.user
    # 添加购物车
    def add(self,request):
        expire_id = 0  #表示永久有效
        # user_id:{course_id:expire, }a
        # user_id = 1
        user_id = request.user.id
        course_id = request.data.get('course_id')

        # 到底有没有这个课程
        try:
            course_obj = Course.objects.get(id=course_id)
        except:
            # return Response({'error':'该课程不存在'}, status=400)
            return Response({'error':'该课程不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 保存购物车数据
        conn = get_redis_connection('cart')
        # 添加购物车之前，先判断一下课程是否已经在购物车中
        ret = conn.hget(user_id,course_id)
        if ret:
            cart_len = conn.hlen(user_id)
            return Response({'error': '该课程已在购物车中','cart_len': cart_len }, status=status.HTTP_400_BAD_REQUEST)


        conn.hset(user_id, course_id, expire_id)
        # conn.hgetall()
        cart_len = conn.hlen(user_id)

        return Response({'msg': '购物车添加成功','cart_len': cart_len })


    # 获取购物车数据
    def cart_list(self,request):
        try:
            user_id = request.user.id
            conn = get_redis_connection('cart')
            cart_redis_data = conn.hgetall(user_id)

            selected_course = conn.smembers(f'selected_{user_id}')  #所有选中课程

            cart_data = []
            for course_bytes_id, expire_bytes_id in cart_redis_data.items():

                # if course_bytes_id in selected_course:
                #     seleced_status = True
                # else:
                #     seleced_status = False
                course_id = course_bytes_id.decode()
                expire_id = int(expire_bytes_id.decode())
                course_obj = Course.objects.get(id=course_id)

                cart_data.append({
                    'id': course_id,
                    'course_img': course_obj.new_course_img_url,  # course_obj.course_img拿到的是imagefield对象,
                    # 通过.url来获取路径值
                    'name': course_obj.name,
                    'price': course_obj.price,
                    'real_price': course_obj.real_price(expire_id),
                    'expire': expire_id,
                    'expire_list':course_obj.course_expire_list,
                    'selected': course_bytes_id in selected_course,

                })

        # print(cart_data)

            return Response(cart_data)

        except:
            return Response({'error':'购物车数据获取失败，请联系管理员'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    #切换有效期
    def change_expire_id(self,request):
        user_id = request.user.id
        course_id = request.data.get('course_id')
        expire_id = request.data.get('expire_id')
        conn = get_redis_connection('cart')

        try:
           course_obj = Course.objects.get(id=course_id)
           if expire_id >0:
                expire_obj = CourseExpire.objects.get(id=expire_id)
        except:
            return Response({'error':'对应课程或有效期选项不存在'}, status=400)

        conn.hset(user_id,course_id,expire_id,)  #修改有效期
        real_price = course_obj.real_price(expire_id)


        return Response({'msg': '有效期切换成功！','real_price':real_price})


    def change_select_status(self,request):
        user_id = request.user.id
        course_id = request.data.get('course_id')
        selected = request.data.get('selected')

        conn = get_redis_connection('cart')
        if selected:

            conn.sadd(f'selected_{user_id}', course_id)
        else:
            conn.srem(f'selected_{user_id}', course_id)

        return Response({'msg': '切换成功'})


        # user_id:{1,2}  #
    def delete_cart_course(self,request):
        user_id = request.user.id
        course_id = request.query_params.get('course_id')

        conn = get_redis_connection('cart')
        pipe = conn.pipeline()
        pipe.multi()
        pipe.srem(f'selected_{user_id}', course_id)
        pipe.hdel(user_id, course_id)
        pipe.execute()
        cart_length = conn.hlen(user_id)

        return Response({'msg': 'ok', 'cart_length':cart_length})




class JieSuanView(ViewSet):

    def get_jiesuan_data(self,request):
        # try:
        user_id = request.user.id
        conn = get_redis_connection('cart')
        cart_redis_data = conn.hgetall(user_id)

        selected_course = conn.smembers(f'selected_{user_id}')  #所有选中课程

        res_data = {}
        jiesuan_data = []
        total_price = 0
        for course_bytes_id, expire_bytes_id in cart_redis_data.items():

            if course_bytes_id in selected_course:

                course_id = course_bytes_id.decode()
                expire_id = int(expire_bytes_id.decode())
                course_obj = Course.objects.get(id=course_id)
                r_price = float(course_obj.real_price(expire_id))
                if expire_id > 0:
                    expire_text = CourseExpire.objects.get(id=expire_id).expire_text
                else:
                    expire_text = '永久有效'
                jiesuan_data.append({
                    'id': course_id,
                    'course_img': course_obj.new_course_img_url,  # course_obj.course_img拿到的是imagefield对象,
                    # 通过.url来获取路径值
                    'name': course_obj.name,
                    'real_price': r_price,
                    'expire_text': expire_text,

                })
                total_price += r_price
        res_data['jiesuan_data'] = jiesuan_data
        res_data['total_price'] = total_price

        return Response(res_data)  #{'jiesuan_data': [], total_price:总价}

        # except:
        #     return Response({'error':'错误'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

